package com.singfan.script;

import org.springframework.beans.BeansException;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 脚本启动类
 * Author: hansonghe
 * Date: 2015-08-19 15:28
 * Desc:
 */
public class Launcher {
    public static void main(String[] args){
        int argsLength = args.length;
        if (argsLength > 0){
            String scriptClassName = args[0];
            try {
                ScriptContext.init();
                Class scriptClazz = Class.forName("com.singfan.script." + scriptClassName);
                List<String> scriptArgList = new ArrayList<>();
                Object scriptObj = ScriptContext.getSpringContext().getBean(scriptClazz);
                Method runMethod = scriptClazz.getMethod("run", List.class);
                if (argsLength >= 2){
                    for (int i=1; i<argsLength; i++){
                        scriptArgList.add(args[i]);
                    }
                }
                Date now = new Date();
                long beginTime = now.getTime();
                System.out.println("-----------------------------------------------------");
                System.out.println(String.format("%1$s开始运行 %2$s", scriptClassName, now));
                runMethod.invoke(scriptObj, scriptArgList);
                Date end = new Date();
                long usedTime = end.getTime() - beginTime;
                System.out.println(String.format("%1$s运行结束 %2$s, 耗时：%3$d", scriptClassName, end, usedTime));
            }
            catch (BeansException e){
                System.out.println(String.format("Launcher.error -> 未找到脚本对象(%1$s)：%2$s !", scriptClassName, e.getMessage()));
            }
            catch (IllegalAccessException e) {
                System.out.println(String.format("Launcher.error -> 实例化脚本对象(%1$s)时发生错误：%2$s !", scriptClassName, e.getMessage()));
            }
            catch (NoSuchMethodException e) {
                System.out.println(String.format("Launcher.error -> 未找到脚本对象(%1$s)的run方法：%2$s !", scriptClassName, e.getMessage()));
            }
            catch (InvocationTargetException e) {
                e.printStackTrace();
                System.out.println(String.format("Launcher.error -> 运行脚本对象(%1$s)的run方法时发生错误：%2$s !", scriptClassName, e.getMessage()));
            }
            catch (ClassNotFoundException e) {
                System.out.println(String.format("Launcher.error -> 没有找到启动脚本(%1$s) !",scriptClassName));
            }
            catch (Exception ex){
                System.out.println(String.format("Launcher.error -> %1$s !", ex.getMessage()));
            }
        }
        else{
            System.out.println("Launcher.error -> 没有指定启动脚本 !");
        }
    }
}
